package com.apadog.study.video.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.apadog.study.utils.RestTemplateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class XiaoHongShuService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static RestTemplate restTemplate = RestTemplateUtil.getInstance();

    private final static HttpHeaders headers = new HttpHeaders();

    static {
        headers.add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
//        headers.add("accept-encoding", "gzip, deflate");
//        headers.add("accept-language", "zh-CN,zh;q=0.9");
//        headers.add("host", "xhslink.com");
//        headers.add("proxy-connection", "keep-alive");
//        headers.add("upgrade-insecure-requests", "1");
        headers.add("upgrade-insecure-requests", "1");
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");

    }
    public static void main(String[] args) {
        // 测试示例
        //String url = "https://www.xiaohongshu.com/discovery/item/68425b2f000000000f03179a?source=webshare&xhsshare=pc_web&xsec_token=CBL-j1bzcZqS85bx4jJziBw_vx59IW1dfjcVgUFUjNh20=&xsec_source=pc_share";
        String url = "https://www.xiaohongshu.com/discovery/item/655e072f000000003202c789?source=webshare&xhsshare=pc_web&xsec_token=ABZrU3Cszk6gmDhhObpY67D1nheCL8g3TbvCofXGAZpus=&xsec_source=pc_share";
        String result = xhs(url);
        System.out.println(result);

    }

    public static String phone(String url){

        HttpHeaders headers = new HttpHeaders();
        headers.set("user-agent","Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1");
        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 发送GET请求
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );
        JSONObject result = new JSONObject();
        try{
            String html =  response.getBody();

            Pattern pattern = Pattern.compile("<script>\\s*window\\.__INITIAL_STATE__\\s*=\\s*(\\{[\\s\\S]*?\\})\\s*</script>",
                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

            Matcher matcher = pattern.matcher(html);

            if (matcher.find()) {
                String jsonData = matcher.group(1);
                // 将 undefined 替换为 null
                jsonData = jsonData.replace("undefined", "null");

                // 解析JSON

                JSONObject decoded = JSONObject.parse(jsonData);

                JSONObject data =  decoded.getJSONObject("noteData").getJSONObject("data").getJSONObject("noteData");
                String type = data.getString("type");
                System.err.println(decoded);

                System.err.println("type："+type);

                JSONArray images = data.getJSONArray("imageList");

                List<String> conveImages = images.stream().map(e->JSONObject.parse(JSON.toJSONString(e)).getString("url")).collect(Collectors.toList());

                System.err.println("type:"+type);
                result.put("type",type);
                if("video".equals(type)){

                    JSONArray videos =  data.
                            getJSONObject("video").
                            getJSONObject("media").
                            getJSONObject("stream").getJSONArray("h264");

                    JSONObject video = JSONObject.parse(JSON.toJSONString(videos.get(0)));
                    System.err.println("video:"+video);
                    List<String> backupUrls = video.getJSONArray("backupUrls").to(List.class);

                    String playUrl = video.getString("masterUrl");


                    data.put("playUrl",playUrl);
                    data.put("conveImages",conveImages);

                    return output(200,"解析成功",result);
                }else if("normal".equals(type)){
                    result.put("images",conveImages);
                    return output(200,"解析成功",result);
                }else {
                    return output(400, "未知类型");
                }

            }
        }catch (Exception e){
            throw new RuntimeException("解析异常");
        }

        return response.getBody();
    }

    public static String xhs(String url) {

        String response = null;
        try {
            // 处理域名转换
            if (url.contains("xhs.com")) {
                String[] parts = url.split("/");
                if (parts.length > 4) {
                    url = "http://xhslink.com/a/" + parts[4];
                }

                // 使用RestTemplate发送HTTP请求
                //response = curl(url);
            }

            response = curl(url);

            if (response == null) {
                return output(400, "请求失败");
            }

            System.err.println("提取连接:"+url);


            //System.err.println(response);
            // 使用正则表达式匹配JSON数据
//            Pattern pattern = Pattern.compile(
//                    "<script>\\s*window\\.__INITIAL_STATE__\\s*=\\s*({[\\s\\S]*?})</script>",
//                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL
//            );
            Pattern pattern = Pattern.compile("<script>\\s*window\\.__INITIAL_STATE__\\s*=\\s*(\\{[\\s\\S]*?\\})\\s*</script>",
                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

            Matcher matcher = pattern.matcher(response);

            if (matcher.find()) {
                String jsonData = matcher.group(1);
                // 将 undefined 替换为 null
                jsonData = jsonData.replace("undefined", "null");

                // 解析JSON

                JSONObject decoded = JSONObject.parse(jsonData);

                JSONObject data = new JSONObject();
                try {
                    JSONObject note = decoded.getJSONObject("note");
                    String id = note.getString("firstNoteId");

                    System.err.println(decoded);
                    JSONObject noteDetailMap = note.getJSONObject("noteDetailMap").getJSONObject(id);



                    JSONObject noteDetailnode = noteDetailMap.getJSONObject("note");

                    String type = noteDetailnode.getString("type");

                    JSONArray images = noteDetailnode.getJSONArray("imageList");

                    List<String> conveImages = images.stream().map(e->JSONObject.parse(JSON.toJSONString(e)).getString("urlDefault")).collect(Collectors.toList());

                    System.err.println("type:"+type);

                    data.put("type",type);

                    if("video".equals(type)){

                        JSONArray result =  noteDetailnode.
                                getJSONObject("video").
                                getJSONObject("media").
                                getJSONObject("stream").getJSONArray("h264");

                        if(result.isEmpty()){
                            return output(400, "h264 解析失败");
                        }

                        JSONObject video = JSONObject.parse(JSON.toJSONString(result.get(0)));
                        System.err.println("video:"+video);
                        List<String> backupUrls = video.getJSONArray("backupUrls").to(List.class);

                        String playUrl = video.getString("masterUrl");


                        data.put("playUrl",playUrl);
                        data.put("conveImages",conveImages);

                        return output(200,"解析成功",data);

                    }else if("normal".equals(type)){
                        data.put("images",conveImages);
                        return output(200,"解析成功",data);
                    }else {
                        return output(400, "未知类型");
                    }

                } catch (Exception e) {
                    // 如果路径不存在，返回空字符串
                    //return output(400, "解析失败: " + e.getMessage());
                    return phone(url);
                }

            } else {
                //return output(400, "未找到 JSON 数据");
                return phone(url);
            }

        } catch (Exception e) {
            return phone(url);
            //return output(400, "解析失败: " + e.getMessage());
        }
    }

    private static String getNodeText(JsonNode node, String... path) {
        try {
            JsonNode current = node;
            for (String key : path) {
                if (current.isArray() && key.matches("\\d+")) {
                    current = current.get(Integer.parseInt(key));
                } else {
                    current = current.get(key);
                }
                if (current == null) return "";
            }
            return current.asText("");
        } catch (Exception e) {
            return "";
        }
    }

    public static String curl(String url) {
        try {
            // 设置请求头

            // 创建请求实体
            HttpEntity<String> entity = new HttpEntity<>(headers);

            // 发送GET请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    String.class
            );
            URI location = response.getHeaders().getLocation();
//            System.err.println(location);
//            System.err.println(JSON.toJSON(response));
//            System.err.println(response);
            System.err.println(location);
            return response.getBody();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String output(int code, String msg) {
        return output(code, msg, new HashMap<>());
    }

    public static String output(int code, String msg, Map<String, Object> data) {
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code", code);
            result.put("msg", msg);
            result.put("data", data);
            return objectMapper.writeValueAsString(result);
        } catch (Exception e) {
            return "{\"code\":500,\"msg\":\"JSON序列化失败\",\"data\":{}}";
        }
    }

}
